package com.asen.commons.core.jdbc.handler;

import com.asen.commons.core.base.model.BaseEnumEntry;
import com.asen.commons.core.base.ObjectEnum;

import java.sql.*;
import java.util.Collection;

/**
 * Date 类型处理器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-02
 */
public class IntegerTypeHandler extends BaseTypeHandler<Integer> {

    @Override
    public int getSqlType() {
        return Types.INTEGER;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer parameter)
            throws SQLException {
        ps.setInt(i, parameter);
    }

    @Override
    public Integer getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return rs.getInt(columnName);
    }

    @Override
    public Integer getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return rs.getInt(columnIndex);
    }

    @Override
    public Integer getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return cs.getInt(columnIndex);
    }

    @Override
    public String toSqlValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Integer) {
            return value.toString();
        }

        if (value instanceof String) {
            return value.toString();
        }

        if (value instanceof String[]) {
            return getSqlValue((String[]) value, false);
        }

        if (value instanceof Integer[]) {
            return getSqlValue((Integer[]) value);
        }

        if (value instanceof Collection) {
            return getSqlValue((Collection) value, false);
        }

        if (value instanceof ObjectEnum) {
            return String.valueOf(((ObjectEnum) value).getValue());
        }

        return String.valueOf(value);
    }

    @Override
    public Integer getValue(Object value) {
        if (value == null) {
            return null;
        }

        if (Integer.class.isAssignableFrom(value.getClass())) {
            return (Integer) value;
        }

        if (ObjectEnum.class.isAssignableFrom(value.getClass())) {
            ObjectEnum actualValue = (ObjectEnum) value;
            return Integer.valueOf(actualValue.getValue().toString());
        }

        if (Boolean.class.isAssignableFrom(value.getClass())) {
            Boolean actualValue = (Boolean) value;
            return Boolean.TRUE.equals(actualValue) ? 1 : 0;
        }

        if (BaseEnumEntry.class.isAssignableFrom(value.getClass())) {
            BaseEnumEntry actualValue = (BaseEnumEntry) value;
            return Integer.valueOf(actualValue.getValue());
        }

        return Integer.valueOf(value.toString());
    }
}
